<template>
  <a-modal @cancel="close" :title="`续交${form.insureKind == 0 ? '交强险' : '商业险'}`" width="75vw" :visible="visible" unmount-on-close>
    <!-- 交强险 -->
    <div class="insure-edit-content">
      <page-form :model="form" ref="formRef" layout="vertical">
        <compulsory-item v-if="form.insureKind == 0" :info="form" operateType="editInsure">
          <i-separate-range-picker
            :popupContainer="'#app'"
            v-model="form.dateRange"
            class="w-full"
            @change="(val) => changeDateFn(val, item)"
          />
        </compulsory-item>
        <!-- 商业险 -->
        <business-item v-if="form.insureKind == 1" :info="form" operateType="editInsure">
          <i-separate-range-picker
            :popupContainer="'#app'"
            v-model="form.dateRange"
            class="w-full"
            @change="(val) => changeDateFn(val, item)"
          />
        </business-item>
      </page-form>
    </div>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="saveFn">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup name="InsureRenewalModal">
  import { ref } from 'vue'
  import compulsoryItem from '@/views/assets/operation/car-insure/components/insurance-policy/compulsory-item.vue'
  import businessItem from '@/views/assets/operation/car-insure/components/insurance-policy/business-item.vue'
  import { carInsuranceDetail, renewInsure } from '@/api/asset/carInsure.js'
  import { Notification } from '@arco-design/web-vue'
  import dayjs from 'dayjs'
  // emit 事件
  const emit = defineEmits(['ok'])
  const visible = ref(false)
  // 修改
  const form = ref({})
  const open = (record) => {
    form.value = {}
    visible.value = true
    carInsuranceDetail({ id: record.id }).then((res) => {
      const result = res.result
      // 续保操作 需要处理 endDate 为 startDate
      // 将当前保险结束日期+1天作为开始日期
      const beginDate = dayjs(result.endDate).add(1, 'day').format('YYYY-MM-DD')
      result.beginDate = beginDate
      result.dateRange = [result.beginDate, '']
      result.endDate = undefined
      result.policyImgFileId = undefined
      form.value = result
    })
  }
  // 日期修改
  const changeDateFn = (value = []) => {
    form.value.beginDate = value[0]
    form.value.endDate = value[1]
  }
  // 关闭
  const close = () => {
    visible.value = false
  }
  // 保存
  const formRef = ref()
  const saveFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        renewInsure(form.value).then(() => {
          close()
          Notification.success({
            content: '保存成功',
            closable: true,
            duration: 3000,
          })
          emit('ok')
        })
      }
    })
  }
  defineExpose({
    open,
  })
</script>
<style lang="less" scoped>
  .insure-edit-content {
    overflow-x: hidden;
    max-height: 80vh;
  }
</style>
